<script setup>
import {get, post, deleted} from '@/utils/request';

import {ref, reactive, onMounted} from "vue";
import {useRoute, useRouter} from 'vue-router'
import {showNotify, closeNotify} from 'vant';

import * as echarts from "echarts";
import {parseMonth, parseDay} from "@/utils/DateUtil.js";
import dayjs from "dayjs";

const router = useRouter();
const route = useRoute()

const nameParam = route.query.name;
const categoryeParam = route.query.category;
const activeTabeParam = route.query.activeTab;
const searchDateParam = route.query.searchDate;


let data = reactive({
  jiZhangTable: [],
  homeStatisticsData: {
    currentMonthCount: 0,
    currentMonthBilling: 0
  },
  search: "",
  dates: [],
  category: "",
  purchaser: "",
  defaultDates: []
})

console.log(activeTabeParam, searchDateParam)
if (activeTabeParam === '月统计') {
  const year = searchDateParam[0];
  const month = searchDateParam[1];
  const d = dayjs(`${year}-${month}`, 'YYYY-MM');
  let begind = d.startOf("month")
  const endDate = d.endOf("month")
  while (begind.isBefore(endDate)) {
    data.dates.push(begind.format("YYYY-MM-DD"));
    data.defaultDates.push(begind.toDate())
    begind = begind.add(1, "day");
    console.log(begind)
  }
}
if (activeTabeParam === '年统计') {
  const year = searchDateParam[0];
  const d = dayjs(`${year}`, 'YYYY');
  let begind = d.startOf("year")
  const endDate = d.endOf("year")
  while (begind.isBefore(endDate)) {
    data.dates.push(begind.format("YYYY-MM-DD"));
    data.defaultDates.push(begind.toDate())
    begind = begind.add(1, "day");
    console.log(begind)
  }

}

if (categoryeParam != null) {
  if (categoryeParam === "1") {
    data.category = nameParam;
  }
  if (categoryeParam === "2") {
    data.purchaser = nameParam;
  }
}


let date = new Date();
const show = ref(false);

post("/api/book/list", {
  "dates": data.dates,
  "productCategory": data.category,
  "purchaser": data.purchaser,
}).then((res) => {
  data.jiZhangTable = res.data;
})

get("/api/book/homeStatistics")
    .then((res) => {
      data.homeStatisticsData = res.data;
    })

function toAddRecord() {
  router.push("/addRecord")
}

function toStatistics() {
  router.push("/statistics")
}


const formatDate = (date) => {
  return `${date.getFullYear()}-${parseMonth(date.getMonth())}-${parseDay(date.getDate())}`;
};
const loading = ref(false);

const onConfirm = (values) => {
  show.value = false;
  data.dates = values.map(item => {
    return formatDate(item);
  })
  onSearch()
};
const onSearch = () => {
  post("/api/book/list", {
    dates: data.dates,
    key: data.search,
    "productCategory": data.category,
    "purchaser": data.purchaser,
  }).then((res) => {
    data.jiZhangTable = res.data;
    loading.value = false
  })
}


const onPrint = () => {


  post("/api/book/download", {
    dates: data.dates,
    key: data.search
  }).then(data => {
    let fileName = "送货详情.xls";
    console.log(data.data)
    const dom = document.createElement('a')
    dom.href = data.data;
    dom.download = decodeURIComponent(fileName)
    dom.style.display = 'none'
    document.body.appendChild(dom)
    dom.click()
    dom.parentNode.removeChild(dom)
  })

};

const updateRecordClick = (id) => {
  router.push({name: 'addRecord', query: {id: id}})
}
const onRemove = (id) => {
  deleted('/api/book/removeById/' + id)
      .then(res => {
        showNotify("删除成功");
        onRefresh()
      })
}
// 下拉刷新
const onRefresh = () => {
  onSearch()
  get("/api/book/homeStatistics")
      .then((res) => {
        data.homeStatisticsData = res.data;
      })
};
const offset = ref({x: document.body.clientWidth, y: 200});


// 日历显示记账个数
let dayCount = new Map();

const getDayCount = async (ym) => {
  console.log('获取数据', ym)
  let response = await get("/api/book/monthDayNum", {
    ym
  });
  for (const item of response.data) {
    dayCount.set(item.day, item.num)
  }
}
// 默认加载当月

onMounted(async () => {
  offset.value.x = document.body.clientWidth * 300 / 375;
  offset.value.y = window.innerHeight * 300 / 375;
  getDayCount(date.getFullYear())
})
const calenDarFormatter = (day) => {
  const year = day.date.getFullYear();
  const month = parseMonth(day.date.getMonth());
  const daa = day.date.getDate();

  let num = dayCount.get(year + '-' + month + '-' + daa);
  if (num != null && num > 0) {
    day.topInfo = num;
    //day.className = "red";
  }

  return day;
};
const onPanelChange = async (day) => {
  /* const year = day.date.getFullYear();
   const month = parseMonth(day.date.getMonth());
   await getDayCount(year + "-" +month)*/

}
// 类别
const showCategoryPicker = ref(false);
const categorycolumns = [
  {text: '全部', value: 'all'},
  {text: '大', value: '大'},
  {text: '中', value: '中'},
  {text: '小', value: '小'}
];
const onCategoryConfirm = ({selectedValues}) => {
  data.category = selectedValues.join(',')
  if (data.category === 'all') {
    data.category = "";
  }
  showCategoryPicker.value = false;
  onSearch()
};


const showPurchasersPicker = ref(false);
let purchasersColumn = [{text: '全部', value: 'all'}]
get("/api/book/listPurchaser")
    .then(res => {
      data.purchasers = res.data;
      for (const item of res.data) {
        purchasersColumn.push({
          text: item,
          value: item,
        })
      }
    });
const onPurchaseConfirm = ({selectedValues}) => {
  data.purchaser = selectedValues.join(',')
  if (data.purchaser === 'all') {
    data.purchaser = "";
  }
  showPurchasersPicker.value = false;
  onSearch()
};
</script>

<template>
  <div id="index">
    <div class="title">
      <van-nav-bar>
        <template #left>
          <h3>日常账本</h3>
        </template>
      </van-nav-bar>
    </div>

    <van-pull-refresh v-model="loading" @refresh="onRefresh">

      <div class="tongji" @click="toStatistics">
        <div class="currentMonthCount">
          本月送货: {{ data.homeStatisticsData.currentMonthCount || '0' }}
        </div>
        <div class="currentMonthBilling">
          本月未开票:
          <span style="color: red">
          {{ data.homeStatisticsData.currentMonthBilling || '0' }}
        </span>

        </div>
      </div>
      <div class="addBtn">
        <van-button type="primary" block @click="toAddRecord">
          添加一条新纪录
        </van-button>
      </div>
      <div class="searchBtn" style="text-align: right;margin-right: 8px;margin-top: 11px;">
        <van-search v-model="data.search" placeholder="请输入搜索关键词" @search="onSearch">
          <template #left>
            <van-button plain icon="calendar-o" hairline color="#000000" size="small" @click="show = true">
              日期
            </van-button>
          </template>
        </van-search>
        <div>
          <van-field
              v-model="data.category"
              is-link
              readonly
              @click="showCategoryPicker = true"
              label="型号"
              placeholder="选择型号"
          >型号
          </van-field>
          <van-field
              v-model="data.purchaser"
              is-link
              readonly
              @click="showPurchasersPicker = true"
              label="采购商"
              placeholder="选择采购商"
          >采购商
          </van-field>
        </div>
      </div>
      <div class="records">
        <div v-for="(itemMap,index) in data.jiZhangTable">
          <van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }">
            {{ itemMap[0].bookDate }}
          </van-divider>
          <van-swipe-cell v-for="item in itemMap">

            <van-card
                :num="item.quantity"
                :desc="'型号:'+item.productCategory"
                :title="item.productName"
                thumb="/qiazi.png"
                @click="updateRecordClick(item.id)"
            >
              <template #tags>
                <van-tag plain type="primary">采购商:{{ item.purchaser }}</van-tag>
                <van-tag plain type="primary">经办人:{{ item.director }}</van-tag>
              </template>
              <template #price>
                <van-space :size="20">
                  <van-button
                      :type="item.recordType==='未开票'?'danger':''"
                      :plain="item.recordType!=='未开票'"
                      :hairline="item.recordType!=='未开票'"
                      size="mini">{{ item.recordType }}
                  </van-button>
                  <span>
            {{ item.bookDate }}
          </span>
                </van-space>

              </template>
            </van-card>
            <template #right>
              <van-button square text="删除" type="danger" class="delete-button" @click="onRemove(item.id)"/>
            </template>
          </van-swipe-cell>
        </div>
      </div>
    </van-pull-refresh>
    <van-calendar
        v-model:show="show"
        type="multiple"
        switch-mode="year-month"
        @close="show = false"
        @panel-change="onPanelChange"
        :formatter="calenDarFormatter"
        :default-date="data.defaultDates"
        @confirm="onConfirm"/>
  </div>
  <van-floating-bubble
      axis="xy"
      icon="orders-o"
      magnetic="x"
      v-model:offset="offset"
      @click="onPrint"/>

  <van-popup v-model:show="showCategoryPicker" round position="bottom">
    <van-picker
        :columns="categorycolumns"
        @cancel="showCategoryPicker = false"
        @confirm="onCategoryConfirm"
    />
  </van-popup>

  <van-popup v-model:show="showPurchasersPicker" round position="bottom">
    <van-picker
        :columns="purchasersColumn"
        @cancel="showPurchasersPicker = false"
        @confirm="onPurchaseConfirm"
    />
  </van-popup>
</template>

<style>
.tongji {
  background-color: rgba(221, 239, 241, 1);
  margin: 8px;
  padding: 8px 0px;
}

.delete-button {
  height: 100%;
}

.tongji > div {
  margin-top: 5px;
}

.addBtn {
  margin: 0 1vw;
}

.red .van-calendar__top-info {
  color: red;
}
</style>